﻿<%@ WebHandler Language="C#" Class="IncomeSummary" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;

public class IncomeSummary : AjaxHandlerBase
{
    public IncomeSummary()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_IncomeSummary_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                case "getlist":
                    GetList(context);
                    break;
                case "getdetails":
                    GetDetails(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetDetails(HttpContext context)
    {
        string year = "";
        string month = "";

        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string[] list = context.Request["ActualDate"].Split('-');
            year = list[0];
            month = list[1].TrimStart('0');
        }
        else
        {
            year = DateTime.Now.Year.ToString();
            month = DateTime.Now.Month.ToString();
        }
        string depid = context.Request["depid"];
        string type = context.Request["typedate"];
        
        //查询条件
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string strSql = "";

        if (type == "1")
            strSql = string.Format("select contractcode,contractdate,sum(ApportionPayMoney*inorout) as paymoney,'本期' as type from v_Report_Commission_FinanceSumInfo where departid='{0}' and (payyear='{1}' and paymonth ='{2}') and (ArchivementYear='{1}' and ArchivementMonth ='{2}') group by contractcode,contractdate", depid, year, month);
        else
            strSql = string.Format("select contractcode,contractdate,sum(ApportionPayMoney*inorout) as paymoney,'前期' as type from v_Report_Commission_FinanceSumInfo where departid='{2}' and ((ArchivementYear='{0}' and ArchivementMonth <'{1}') or (ArchivementYear<'{0}')) and (payyear='{0}' and paymonth ='{1}') group by contractcode,contractdate", year, month, depid);
            
        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }

    private void GetList(HttpContext context)
    {
        string year = "";
        string month = "";

        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string[] list = context.Request["ActualDate"].Split('-');
            year = list[0];
            month = list[1].TrimStart('0');
        }
        else
        {
            year = DateTime.Now.Year.ToString();
            month = DateTime.Now.Month.ToString();
        }

        //查询条件
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomeSummary_Search_All))
        {
            sb.Append(" (1=1) ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomeSummary_Search_City))
        {
            sb.AppendFormat(" (a.DepartId in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", CurrentUserInfo.CityId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomeSummary_Search_Company))
        {
            sb.AppendFormat(" (a.DepartId in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", CurrentUserInfo.CompanyId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_IncomeSummary_Search_Depart))
        {
            sb.Append(" (EXISTS(");
            sb.AppendFormat("Select 1 from t_Business_EmpSetting M WHERE a.DepartId=M.DepartId And M.Userid= '{0}' and SearchIncomeSummary=1", CurrentUserInfo.UserId.ToString());
            sb.Append(")) ");
        }
        else
            sb.Append(" (1=0) ");


        //点数门店；合同所属
        if (context.Request["type"] == "10")
        {
            //4级
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);

            if (departs != Guid.Empty)
            {
                sb.AppendFormat(" and a.DepartId = '{0}'", departs);
            }
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null)
                {
                    context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
                }
                sb.AppendFormat(" and (a.DepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sb.AppendFormat(" and (a.DepartId in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", company);
            }
            else if (city != Guid.Empty)
            {
                sb.AppendFormat(" and (a.DepartId in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", city);
            }
        }
        else if (context.Request["type"] == "20")
        {
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            if (company != Guid.Empty)
            {
                sb.AppendFormat(" and (a.BargainCompanyId='{0}' or b.BargainCompanyId='{0}') ", company);
            }
        }

        string strSql = "select a.DepartId,business,departname,old_realget,old_cname,now_realget,now_cname,a.BargainCompanyId,b.BargainCompanyId from "
                    + "((select DepartId,dbo.FN_GetBussinessByDepartID(DepartId) as business,dbo.FN_GetDepartNameByDepartID(DepartId) as departname,"
                    + string.Format("sum(case when (payyear='{0}' and paymonth ='{1}') and (ArchivementYear='{0}' and ArchivementMonth ='{1}')   ", year, month)
                    + "then ApportionPayMoney*inorout else 0 end) as now_realget,BargainCompanyId,dbo.FN_GetDepartNameByDepartID(BargainCompanyId) as now_cname "
                    + string.Format(" from dbo.v_Report_Commission_FinanceSumInfo where payyear='{0}' and paymonth ='{1}' group by DepartId,BargainCompanyId )a ",year,month)
                    +"FULL OUTER JOIN "
                    +"(select DepartId,"
                    + string.Format("sum(case when ((ArchivementYear='{0}' and ArchivementMonth <'{1}') or (ArchivementYear<'{0}')) and (payyear='{0}' and paymonth ='{1}') ", year, month)
                    + "then ApportionPayMoney*inorout else 0 end) as old_realget,BargainCompanyId,dbo.FN_GetDepartNameByDepartID(BargainCompanyId) as old_cname "
                    + string.Format(" from dbo.v_Report_Commission_FinanceSumInfo where payyear='{0}' and paymonth ='{1}' group by DepartId,BargainCompanyId )b",year,month)
                    +" on a.departid=b.departid ) where "+sb.ToString();

        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }
}